package components
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	/**
	 * @author perry
	 */
	public class ECGDataLoader extends Sprite
	{
		public static const NAME:String 				 = "ECGDataLoader";
		public static const COMPLETE:String				 = NAME + "Complete";
		public static const DATA_LOADED:String			 = NAME + "DataLoaded";
		
		private const BEAT_RATIO:Number 				 = 0.5;
		
		private var ECGdata:Vector.<ECGSignal>;
		private var values:Array;
		private var rawECGData:String;
		
		private var loaderTask:String;
		
		private var beat:int;
		private var beating:Boolean;
		
		public function ECGDataLoader()
		{
			
		}
		
		public function init( path:String ):void
		{
			beat = 0;
			
			var l:URLLoader = new URLLoader();
			l.addEventListener( Event.COMPLETE, ECGDataCompleteHandler );
			l.load( new URLRequest( path ) );
		}
		
		public function precision( val:int ):Vector.<ECGSignal>
		{
			var arr:Vector.<ECGSignal> = new Vector.<ECGSignal>();
			
			var i:uint;
			for( i = 0; i < ECGdata.length; i++ )
			{
				if( i == 0 ) arr.push( ECGdata[i] );
				else
				{
					if( i + val > ECGdata.length ) break;
					
					arr.push( ECGdata[i + val] );
					
					i += val;
				}
			}
			
			return arr;
		}
		
		private function ECGDataCompleteHandler( e:Event ):void
		{
			loaderTask = "Parsing data";
			dispatchEvent( new Event( DATA_LOADED ) );
			
			rawECGData = e.target.data;
			
			rawECGData = UTILS.strReplace(rawECGData, "  ", " ");
			rawECGData = UTILS.strReplace(rawECGData, "	", " ");
			
			values = rawECGData.split("\n");
			
			var sig:ECGSignal;
			var subVal:Array;
			ECGdata = new Vector.<ECGSignal>();
			
			var i:uint;
			for( i = 2; i < values.length; i++ )
			{
				subVal = values[i].split("  ");
				
				sig = new ECGSignal();
				sig.t = subVal[0];
				sig.mV = subVal[1] * -1;
				
				if( sig.mV > BEAT_RATIO && !beating )
				{
					beat++;
					beating = true;
				}
				
				if( sig.mV < 0 && beating )
				{
					beating = false;
				}
					
				sig.beat = beat;
				
				ECGdata.push( sig );
			}

			dispatchEvent( new Event( COMPLETE ) );
		}
		
		public function get data():Vector.<ECGSignal>
		{
			return ECGdata;
		}
		
		public function get rawData():String
		{
			return rawECGData;
		}
		
		public function get task():String
		{
			return loaderTask;
		}
	}
}
